package com.sdkj.fixed.asset.hc.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.hc.ProductApi;
import com.sdkj.fixed.asset.api.hc.vo.in.IdParams;
import com.sdkj.fixed.asset.api.hc.vo.in.StatisticsParams;
import com.sdkj.fixed.asset.api.hc.vo.out.CategotryProduct;
import com.sdkj.fixed.asset.api.hc.vo.out.ProductStatistics;
import com.sdkj.fixed.asset.api.hc.vo.out.Statistics;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.FileDownload;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.mapper.CategoryProductMapper;
import com.sdkj.fixed.asset.hc.mapper.OrgManagementMapper;
import com.sdkj.fixed.asset.hc.mapper.ProductMapper;
import com.sdkj.fixed.asset.hc.mapper.ProductTypeMapper;
import com.sdkj.fixed.asset.hc.service.ProductService;
import com.sdkj.fixed.asset.hc.util.CacheUtil;
import com.sdkj.fixed.asset.hc.util.ExcelUtils;
import com.sdkj.fixed.asset.hc.util.QiniuService;
import com.sdkj.fixed.asset.pojo.hc.Category;
import com.sdkj.fixed.asset.pojo.hc.CategoryProduct;
import com.sdkj.fixed.asset.pojo.hc.Product;
import com.sdkj.fixed.asset.pojo.hc.Qwert;
import com.sdkj.fixed.asset.pojo.hc.group.*;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 史晨星
 * @ClassName: ProductController
 * @Description: 物品档案
 * @date 2020年7月20日
 */
@Validated
@RestController()
public class ProductController extends BaseController<Product> implements ProductApi {

    private static Logger log = LoggerFactory.getLogger(ProductController.class);

    @Resource
    private ProductService service;

    @Resource
    private ProductTypeMapper productTypeMapper;

    @Resource
    private ProductMapper mapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Resource
    private HttpServletRequest request;

    @Override
    public BaseService<Product> getService() {
        return service;
    }

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private QiniuService qiniuService;

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo add(@Validated({AddProduct.class}) Product entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCuser(userId);
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setCtime(DateUtil.now());
        entity.setOrgId(orgId);
        entity.setTemporary(2);
        Product product = service.add(entity);
        return BaseResultVo.success("success", product.getId());
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo edit(@Validated({EditProduct.class}) Product entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        Product product = service.edit(entity);
        return BaseResultVo.success("success", product.getId());
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo del(@Validated({DelProduct.class}) Product entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        Product product = service.del(entity);
        return BaseResultVo.success("success", product.getId());
    }

    /**
     * 查看
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo view(@Validated({ViewProduct.class}) Product entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setTemporary(0);
        Product product = service.view(entity.getId());
        return BaseResultVo.success("success", product);
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getPages(PageParams<Product> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setOrgId(orgId);
        if (StrUtil.isBlank(params.getParams().getType())) {
            throw new LogicException("类型id必填");
        }
        List<Product> pageList = service.getPages(params);
        PageBean<Product> page = new PageBean<>(pageList);
        return BaseResultVo.success(page);
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getPagesIn(PageParams<Product> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setOrgId(orgId);
        if (StrUtil.isBlank(params.getParams().getType())) {
            throw new LogicException("类型id必填");
        }
        List<Product> pageList = service.getPagesIn(params);
        PageBean<Product> page = new PageBean<>(pageList);
        return BaseResultVo.success(page);
    }


    /**
     * 根据分类查物品（分页查询）
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getProductByType(@Validated({GetProductByTypeAndCategory.class}) Product params) throws Exception {
        String token = request.getHeader("token");
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        Example example = new Example(Product.class);
        // 条件查询
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("state", 1);
        if (StrUtil.isNotEmpty(params.getName())) {
            criteria.andLike("name", params.getName());
        }
        if (StrUtil.isNotEmpty(params.getType())) {
            criteria.andLike("type", params.getType());
        }
        criteria.andNotEqualTo("temporary", 1);
        example.orderBy("ctime").desc();
        List<Product> productList = mapper.selectByExample(example);
        for (Product product : productList) {
            product.setTypeName(productTypeMapper.selectByPrimaryKey(product.getType()).getName());
            int totalNum = 0;
            Example example1 = new Example(CategoryProduct.class);
            // 条件查询
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("productId", product.getId());
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example1);
            for (CategoryProduct categoryProduct : categoryProducts) {
                totalNum += categoryProduct.getProductNum();
            }
            product.setTotalNum(totalNum);
        }
        return BaseResultVo.success(productList);
    }

    /**
     * 根据分类和仓库查物品（分页查询）
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getProductByTypeAndCategory(@Validated({GetProductByTypeAndCategory.class}) PageParams<Product> params) throws Exception {
        List<CategotryProduct> pageList = service.getProductByTypeAndCategory(params);
        PageBean<CategotryProduct> page = new PageBean<>(pageList);
        return BaseResultVo.success("success", page);
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo saveImg(MultipartFile file) throws Exception {
        String fileName = "GZGL_" + IdUtil.fastSimpleUUID();
        String s = qiniuService.saveImage(file, fileName);
        return BaseResultVo.success("success", s);
    }

    /**
     * 下载物品模板
     *
     * @param response
     * @throws Exception
     */
    @Override
    public void downTemp(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, request, getClass().getResource("/").getPath() + "/template/耗材物品导入模板.xlsx", "耗材物品导入模板.xlsx");
    }

    /**
     * 导入用户
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo importProduct(MultipartFile file) throws Exception {
        String token = request.getHeader("token");
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        String userId = cacheUtil.getUser(token).getUserId();
        if (file == null) {
            throw new LogicException("文件不能为空");
        }
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            throw new LogicException("文件类型必须为【.xlsx】");
        }
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new LogicException("文件最大允许10MB");
        }
        service.importProduct(file, orgId, userId);
        return BaseResultVo.success();
    }


    /**
     * 导出
     *
     * @param companyId
     * @param response
     * @throws Exception
     */
    @Override
    public void export(String companyId, String type, HttpServletResponse response) throws Exception {
        Product product = new Product();
        product.setOrgId(companyId);
        product.setType(type);
        List<Product> list = service.getAll(product);
        String fileName = "耗材物品" + TimeTool.getTimeDate14();
        ExcelUtils.exportExcel(list, Product.class, fileName, response);
    }

    /**
     * 报表
     *
     * @param
     * @return
     */
    @Override
    public BaseResultVo statistics(PageParams<StatisticsParams> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setUserId(userId);
        params.getParams().setOrgId(orgId);

        if (StrUtil.isNotBlank(params.getParams().getStart())) {
            byte[] space = new byte[]{(byte) 0xc2, (byte) 0xa0};
            String UTFSpace = null;
            try {
                UTFSpace = new String(space, "utf-8");
            } catch (Exception e) {
                log.error("", e);
            }
            // 这里的smsContent就是前端传过来的包含乱码的值。
            params.getParams().setStart(params.getParams().getStart().replace(UTFSpace, " "));
            params.getParams().setEnd(params.getParams().getEnd().replace(UTFSpace, " "));
        }

        List<ProductStatistics> products = service.statistics(params);
        PageBean<ProductStatistics> page = new PageBean<>(products);
        return BaseResultVo.success("success", page);
    }

    /**
     * 仓库下物品
     *
     * @param
     * @return
     */
    @Override
    public BaseResultVo getProductByCategory(IdParams params) throws Exception {
        List<Product> products = service.getProductByCategory(params);
        return BaseResultVo.success("success", products);
    }

    /**
     * 报表
     *
     * @param
     * @return
     */
    @Override
    public BaseResultVo statisticsDetail(PageParams<StatisticsParams> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setUserId(userId);
        params.getParams().setOrgId(orgId);

        if (StrUtil.isNotBlank(params.getParams().getStart())) {
            byte[] space = new byte[]{(byte) 0xc2, (byte) 0xa0};
            String UTFSpace = null;
            try {
                UTFSpace = new String(space, "utf-8");
            } catch (Exception e) {
                log.error("", e);
            }
            // 这里的smsContent就是前端传过来的包含乱码的值。
            params.getParams().setStart(params.getParams().getStart().replace(UTFSpace, " "));
            params.getParams().setEnd(params.getParams().getEnd().replace(UTFSpace, " "));
        }

        List<Qwert> result = service.statisticsDetail(params);
        PageBean<Qwert> page = new PageBean<>(result);
        return BaseResultVo.success("success", page);
    }

    /**
     * 导出
     *
     * @param userId
     * @param categoryId
     * @param start
     * @param end
     * @param name
     * @param response
     * @throws Exception
     */
    @Override
    public void exportStatistics(String orgId, String userId, String categoryId, String start, String end, String name, HttpServletResponse response) throws Exception {
        StatisticsParams params = new StatisticsParams();
        params.setUserId(userId);
        params.setCategoryId(categoryId);
        params.setStart(start);
        params.setEnd(end);
        params.setName(name);
        params.setOrgId(orgId);
        List<ProductStatistics> products = service.export(params);
        String fileName = "收发存汇总表";
        ExcelUtils.exportExcel(products, ProductStatistics.class, fileName, response);
    }

    /**
     * 导出
     *
     * @param userId
     * @param categoryId
     * @param start
     * @param end
     * @param productId
     * @param response
     * @throws Exception
     */
    @Override
    public void exportStatisticsDetail(String orgId, String userId, String categoryId, String start, String end, String productId, HttpServletResponse response) throws Exception {
        StatisticsParams params = new StatisticsParams();
        params.setUserId(userId);
        params.setCategoryId(categoryId);
        params.setStart(start);
        params.setEnd(end);
        params.setProductId(productId);
        params.setOrgId(orgId);
        List<Qwert> result = service.exportDetail(params);
        String fileName = "收发存明细表";
        ExcelUtils.exportExcel(result, Qwert.class, fileName, response);
    }
}

